package com.cdtye.itps.cms.service.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cdtye.common.kafkacore.model.enums.KfkBizKeyEnum;
import com.cdtye.common.kafkacore.service.KfkProducerRecordService;
import com.cdtye.common.mongocore.query.Page;
import com.cdtye.itps.cms.dao.datasysn.Defect;
import com.cdtye.itps.cms.dao.defect.entity.JcwProblemDefectInfo;
import com.cdtye.itps.cms.dao.defect.vo.JcwProblemDefectInfoVo;
import com.cdtye.itps.cms.dao.detect.RestJson;
import com.cdtye.itps.cms.service.datasysn.PlanDetailTmisService;
import com.cdtye.itps.cms.service.defect.JcwProblemDefectInfoService;
import com.cdtye.itps.cms.service.defect.SysTaskService;
import com.cdtye.itps.cms.util.DateUtils;
import com.cdtye.itps.models.base.model.attr.defect.DefectPhotoAttr;
import com.cdtye.itps.models.base.model.entity.repair.SysTask;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RefreshScope
@Slf4j
@Service
public class SyncDataJobService {

    @Autowired
    private SysTaskService sysTaskService;
    @Autowired
    private KfkProducerRecordService kfkProducerRecordService;

    @Autowired
    private JcwProblemDefectInfoService jcwProblemDefectInfoService;

    @Autowired
    private PlanDetailTmisService planDetailTmisService;

    //缺陷地址
    @Value("${cdtye.host.6c.defect-sh}")
    private String detectDefectJobUrl;
    //缺陷主题
    @Value("${topic.itps.defect}")
    private String topicDefect;

    //检测缺陷数据时间戳
    public final static String INF_NAME_DEFECT_GZ = "defectJob";

    //检测缺陷Tmis数据时间戳
    public final static String INF_NAME_DEFECT_TMIS = "defectJobTmis";

    private final static String SUCCESS = "200";
    private final static Integer SUCCESS_ZERO = 0;

    public void processDefectInfos(){
        this.requestDefectInfos(detectDefectJobUrl,  KfkBizKeyEnum.ITPS_DEFECT.getKey(), INF_NAME_DEFECT_GZ);
    }

    /**
     * 缺陷数据导入定时请求
     */
    public void requestDefectInfos(String url, String kafkaKey, String sysTaskInf) {
        XxlJobLogger.log("=================================开始任务:缺陷数据导入========================================");
        log.info("=================================开始任务:缺陷数据导入========================================");
        try {

            //获取上次作业时间
            SysTask sysTask = sysTaskService.findByInfName(sysTaskInf);
            //组装url
            HashMap<String, String> map = new HashMap<>(3);
            String startTime = null;
            if (sysTask != null) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                startTime = format.format(sysTask.getLastUpdateTime());
            } else {
                sysTask = new SysTask();
                sysTask.setInfName(sysTaskInf);
                startTime = "2020-01-01 00:00:00";
            }

            int page = 1;
            int pageSize = 500;
            //是否更新作业时间
            boolean sysTaskIf = true;
            Date currDate = new Date();
            String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, currDate);
            url += "&startTime=" + startTime + "&endTime=" + endTime + "&pageSize=" + pageSize + "&pageIndex=";
            while (true) {
                String tempUrl = url + page;
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(tempUrl);
                String finalUrl = builder.build().encode().toString();
                XxlJobLogger.log("进入缺陷数据导入自动请求：" + finalUrl);
                log.info("进入缺陷数据导入自动请求：" + finalUrl);
                CloseableHttpClient HttpClient = null;
                SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
                        SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                        NoopHostnameVerifier.INSTANCE);
                HttpClient = HttpClients.custom().setSSLSocketFactory(scsf).build();
                HttpGet httpGet = new HttpGet(finalUrl);
                CloseableHttpResponse response = HttpClient.execute(httpGet);
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                if (StringUtils.isBlank(result)) {
                    log.info("缺陷作业请求 返回数据为 空......");
                    return;
                }
                log.info("缺陷数据获取到 page==" + page + " result：" + result);
                RestJson<JSONObject> restJson = JSONObject.parseObject(result, RestJson.class);

                if (restJson.getStatus().equals(SUCCESS) || restJson.getStatus().equals(SUCCESS_ZERO)) {
                    List<Defect> list = JSONArray.parseArray(restJson.getData().toString(), Defect.class);
                    if(list == null){
                        break;
                    }
                    // 字段映射
                    List<JSONObject> resultData = restJson.getData();
                    for (int j = 0; j < list.size(); j++) {
                        Defect defect = list.get(j);
                        JSONObject tData = resultData.get(j);
                        JSONArray dealPhotoList = tData.getJSONArray("defectPhoto");
                        if (dealPhotoList != null && dealPhotoList.size() > 0) {
                            List<DefectPhotoAttr> picList = new ArrayList<>();
                            for (int k = 0; k < dealPhotoList.size(); k++) {
                                JSONObject dealPhoto = dealPhotoList.getJSONObject(k);
                                DefectPhotoAttr defectPhotoAttr = new DefectPhotoAttr();
                                defectPhotoAttr.setFileName(dealPhoto.getString("name"));
                                defectPhotoAttr.setFilePath(dealPhoto.getString("photoUrl"));
                                String photoType = dealPhoto.getString("photoType");
                                defectPhotoAttr.setFileType(photoType);
                                if (photoType != null) {
                                    defectPhotoAttr.setFlag(Integer.getInteger(photoType));
                                }
                                picList.add(defectPhotoAttr);
                            }
                            defect.setPicList(picList);
                        }
                    }
                    XxlJobLogger.log("缺陷数据获取到：" + (list == null ? 0 : list.size()) + "条数据");
                    log.info("缺陷数据获取到：" + (list == null ? 0 : list.size()) + "条数据  getTotal===" + restJson.getTotal());
                    kfkProducerRecordService.saveAndSend(topicDefect, kafkaKey, list);
                    //TODO 测试直接入库
                    //ConsumerRecord record = new ConsumerRecord("topic", 0, 0L, "", list);
                    //planDetailService.saveShuoHuangDetailService(record);
                    XxlJobLogger.log(">缺陷数据->请求完成，更新任务记录");
                    if (list.size() < pageSize) {
                        break;
                    }
                    page++;
                } else {
                    XxlJobLogger.log("ERROR==>缺陷数据请求失败：" + restJson.getMessage());
                    log.error("ERROR==>>缺陷数据请求失败：" + restJson.getMessage());
                    sysTaskIf = false;
                }
            }

            //保存更新记录
            if (sysTaskIf) {
                sysTask.setLastUpdateTime(currDate);
                sysTaskService.saveOrUpdate(sysTask);
            }
        } catch (Exception e) {
            XxlJobLogger.log("ERROR==>缺陷数据系统错误：" + e.getMessage());
            XxlJobLogger.log(e);
            log.error("ERROR==>缺陷数据系统错误：" + e.getMessage(), e);
        }
    }

    //Tmis缺陷数据
    public void distributeTmisDefectInfos() {
        this.requestTmisDefectInfos(INF_NAME_DEFECT_TMIS);
    }

    /**
     * Tmis缺陷数据导入定时请求
     */
    public void requestTmisDefectInfos(String sysTaskInf) {
        XxlJobLogger.log("=================================开始任务:缺陷段级数据导入========================================");
        log.info("=================================开始任务:缺陷段级数据导入========================================");
        try {

            Date lastUpdateTime = new Date();
            //获取上次作业时间
            SysTask sysTask = sysTaskService.findByInfName(sysTaskInf);
            if (sysTask != null) {
                lastUpdateTime = sysTask.getLastUpdateTime();
                //在数据库记录的最后修改时间的基础上减7天
                lastUpdateTime = DateUtils.addDay(lastUpdateTime, -7);
            } else {
                XxlJobLogger.log("此任务不存在");
                log.info("此任务不存在");
                return;
            }

            Integer page = 1;
            Integer size = 500;
            JcwProblemDefectInfoVo vo = new JcwProblemDefectInfoVo();
            vo.setPage(page);
            vo.setSize(size);
            vo.setUpdateDatetimeQuery(lastUpdateTime);
            vo.setJobQuery("toSection");
            //当接口同步时，删除状态的数据也需要查询出来
            vo.setDelFlag("toSection");
            IPage<JcwProblemDefectInfo> pages = jcwProblemDefectInfoService.listPageJdgm(vo);

            //是否更新作业时间
            boolean sysTaskIf = true;
            if (pages.getTotal() > 0) {
                List<JcwProblemDefectInfo> list = pages.getRecords();
                XxlJobLogger.log(sysTaskInf + "缺陷Tmis数据获取到：" + (list == null ? 0 : list.size()) + "条数据");
                log.info(sysTaskInf + "缺陷Tmis数据获取到：" + (list == null ? 0 : list.size()) + "条数据");
                planDetailTmisService.handleDefectSection(list, "JDGM");
                Long totalPage = Page.getTotalPage(pages.getTotal(), 500);
                for (Integer i = 2; i <= totalPage; i++) {
                    vo.setPage(i);
                    IPage<JcwProblemDefectInfo> pages2 = jcwProblemDefectInfoService.listPageJdgm(vo);
                    if (pages2.getTotal() > 0) {
                        List<JcwProblemDefectInfo> list2 = pages2.getRecords();
                        XxlJobLogger.log("缺陷Tmis数据第"+i+"页获取到：" + (list2 == null ? 0 : list2.size()) + "条数据");
                        log.info("缺陷Tmis数据第"+i+"页获取到：" + (list2 == null ? 0 : list2.size()) + "条数据");
                        planDetailTmisService.handleDefectSection(list2, "JDGM");
                    }
                }
                XxlJobLogger.log(">缺陷Tmis数据->请求完成，更新任务记录");

            } else {
                XxlJobLogger.log("ERROR==>缺陷Tmis数据请求完成");
                log.error("ERROR==>>缺陷Tmis数据请求完成");
                sysTaskIf = false;
            }
            //保存更新记录
            if (sysTaskIf){
                sysTask.setLastUpdateTime(new Date());
                sysTaskService.saveOrUpdate(sysTask);
            }
        } catch (Exception e) {
            XxlJobLogger.log("ERROR==>缺陷Tmis数据系统错误：" + e.getMessage());
            XxlJobLogger.log(e);
            log.error("ERROR==>缺陷Tmis数据系统错误：" + e.getMessage(), e);
        }
    }
}
